/* Phono Chat */

jQuery(document).ready(function() {
	var connStablished, calls = {}, chats = {}, mySessionInfo;
	
	var showingPlayers=false;
	
	function urlParam(name) {
		var results = new RegExp('[\\?&]' + name + '=([^&#]*)')
				.exec(window.location.href);
		if (!results) {
			return undefined;
		}
		return results[1] || undefined;
	}

	function createNewPhono() {
		//Clone a phono div	
		var phonoCtr = (jQuery(".phono").size() + 1) - 1;
		var newPhonoID = "Phono" + phonoCtr;
		var newPhonoDiv = jQuery('.phono').first();
//		newPhonoDiv.attr("id",newPhonoID).appendTo('.phonoHldr').show();
		newPhonoDiv.find(".phonoID").text(newPhonoID+":");				
		
		connStablished = jQuery.phono({
			apiKey: "eac2e3f059dff315a698ce822deae0e4",
			
			audio: {type:"none"},
			
			onReady: function(event) {
				newPhonoDiv.find(".sessionId").html(this.sessionId);
				newPhonoDiv.find(".phoneControl").show();
				
				//console.log("["+newPhonoID+"] Phono loaded"); 
				jQuery.ajax({
					type:		"POST",
					url:		"chatAPI.php",
					dataType:	"json",
					data:		{method: "connect", sId:this.sessionId},
					success:	function(data) {						
						mySessionInfo=data.myInfo;
						
						jQuery.each(mySessionInfo.friendsList, function(friendId, friendInfo){
							var thisPhono = newPhonoDiv.attr("id");
							friendElement = jQuery("<a></a>");
							friendElement.attr("id", friendId);
							friendElement.text(friendInfo.userName);
							friendElement.click(function(){
								openingChatSession(thisPhono, "chatSessionInfo", friendId, "");	
							});
							newPhonoDiv.find(".phoneControl").append(friendElement);
						});
						
						$.each(mySessionInfo.messagesPending, function(userFrom, chatSessionFrom) {
							$.each(chatSessionFrom.messages, function(index, theMessage) {
								routeMessage(newPhonoID, "inbound", chatSessionFrom, theMessage);
							})
							delete chatSessionFrom.messages;
						});
						
					},
				});
				
				//if(!this.audio.permission()){                  
				//	this.audio.showPermissionBox();
				//}
			},
			
			onUnready: function(event) {				
				newPhonoDiv.find(".sessionId").text("disconnected");
				console.log("[" + newPhonoID + "] Phono disconnected");	
			},
			
			onError: function(event) {
				newPhonoDiv.find(".sessionId").text(event.reason);
				console.log(event.reason);		
			},
			
			messaging: {
                onMessage: function(event, message) {
				
					
            	    var fromSessionId = message.from.split("/");
					var messageWithExtraParam = message.body.split("$#_#$");
					
					chatSession = {
						fromName: messageWithExtraParam[0],
						fromUserId: messageWithExtraParam[1],
						sessionId: fromSessionId[0],
					};
					var realMessage = "";
					for (i=2; i < messageWithExtraParam.length; i++) {
						realMessage +=messageWithExtraParam[i];
						if (i+1<messageWithExtraParam.length) {
							realMessage += "$#_#$";
						}
					}
					
            	    routeMessage("MyChatSession","inbound",chatSession,realMessage);
                }
			}
			
		});
	}
	
	//Routes a message to the appropriate chat or creates a new chat
	function routeMessage(phonoID, type, chatSession, message) {
		
		prefix="";
		if (type == "inbound")
			prefix="from";
		else
			prefix="to";
			
		var theChat = "";
		$.each(chats, function(key, value) {
			if (value["toUserId"] == chatSession[prefix + "UserId"]
				|| value["fromUserId"] == chatSession[prefix + "UserId"]) {
				theChat = key;
				var newMsg = chatMessage(chatSession[prefix + "Name"], message, type);
				var chatDiv = jQuery("#" + theChat);
				renderNewMessage(chatDiv, newMsg);
				chatDiv.find(".chatTxtInput").focus();
				return;
			}
		});
		//Did we find a chat?
		if (!theChat.length) {
			createNewChat(phonoID, type, chatSession, message);
		}
	}

	//Outputs an IM message
	function renderNewMessage(chat, msg) {
		chat.find(".chatBox").append(msg);
		chat.find(".chatBox").attr({
			scrollTop : chat.find(".chatBox").attr("scrollHeight")
		});
	}
	function createNewChat(phonoID, type, chatSession, message) {
	
		prefix="";
		if (type == "inbound")
			prefix="from";
		else
			prefix="to";
		
		//clone a chat box
		var phonoDiv = jQuery("#" + phonoID);
		var newChatID;
		if (jQuery("#Chat_" + chatSession[prefix + "UserId"]).length == 0) {
			newChatID = createChatDiv(phonoID, chatSession[prefix + "UserId"]);
		} else {
			newChatID = "Chat_" + chatSession[prefix + "UserId"];
		}
		var chatDiv = jQuery("#" + newChatID);
		chatDiv.find(".chatID").text(chatSession[prefix + "Name"]);
		if (message.length) {
			var newMsg = chatMessage(chatSession[prefix + "Name"], message, type);
			renderNewMessage(chatDiv, newMsg);
		}
		
		console.log("[" + phonoDiv.attr('id') + "] [" + newChatID
				+ "] Chat started with " + chatSession.sessionId);
		
		// The Session Id is saved in the opened chats.
		chats[newChatID] = chatSession;
	}
	//Creates a new chat
	function openingChatSession(phonoID, type, to, message) {
		jQuery.ajax({
			type:		"POST",
			url:		"chatAPI.php",
			dataType:	"json",
			data:		{method: type, uId: to},
			success:	function(data) {
							createNewChat(phonoID, "outbound", data.chatSession, message);
						}
		});
	}
	

	//Creates a new div to hold a chat. Returns the id of the new div
	function createChatDiv(phonoID, userId) {
		
		if (jQuery('.chats').length == 0) {
			var wrapper = jQuery('<div class="chats"/>');
			jQuery('body').append(wrapper);
			wrapper.click(function(event){
				event.stopPropagation();
			});
		} else {
			var wrapper = jQuery('.chats');
		}
		
		newChatID = "Chat_" + userId;
		
		singleEmptyChat = jQuery('<div id="'+ newChatID +'" class="chatHldr"/>');
		singleEmptyChatHeader = jQuery('<div class="chatHeader"><a class="closeChat" title="Remove" href="#"></a><span class="chatID"></span></div>');
		singleEmptyChatBox = jQuery('<div class="chatBox"></div>');
		singleEmptyChatInput = jQuery('<div class="chatInputHldr"><input class="chatTxtInput" type="text"><input class="sendMsg" type="button" value="send"></div>');
		
		jQuery('.sendMsg', singleEmptyChatInput).click(function(event){
				var thisPhono = $(this).closest(".phono");
				var thisChat = $(this).closest(".chatHldr");
				var msgText = thisChat.find(".chatTxtInput").val();
				var newMsg = chatMessage("You", msgText, "outbound");
				renderNewMessage(thisChat, newMsg);
				toSessionId=chats[thisChat.attr("id")].sessionId;
				msgTextWithParameters = mySessionInfo.myName +"$#_#$"+ mySessionInfo.myUserId +"$#_#$"+ msgText;
				connStablished.messaging.send(toSessionId, msgTextWithParameters);
				jQuery.ajax({
					type:		"POST",
					url:		"chatAPI.php",
					dataType:	"json",
					data:		{method: "outbound", toChatSession: chats[thisChat.attr("id")], message: msgText},
					success:	function(data) {
						chats[thisChat.attr("id")] = data.chatSession;
					},
				});
				thisChat.find(".chatTxtInput").val("");
				console.log("[" + thisPhono.attr('id') + "] Sending message to: "
						+ chats[thisChat.attr('id')] + " [" + msgText + "]");
			});
		
		singleEmptyChat.html(singleEmptyChatHeader);
		singleEmptyChat.append(singleEmptyChatBox);
		singleEmptyChat.append(singleEmptyChatInput);
		
		wrapper.append(singleEmptyChat);
		
		singleEmptyChatHeader.width(singleEmptyChat.width());
		
		return newChatID;
	}
	
	// Create and return a chat message bubble
	var chatMessage = function(from, body, type) {
		var result;
	
		if (type == 'inbound') {
			var borderStyle = "inbound";
			var fromStyle = "fromInbound";
		} else {
			var borderStyle = "outbound";
			var fromStyle = "fromOutbound";
		}
	
		result = jQuery("<div>").addClass("chatEntry").addClass(borderStyle);
		var fromHeader = jQuery("<div>").addClass("from").addClass(fromStyle).html(from)
				.appendTo(result);
		var msgBody = jQuery("<div>").addClass("body").html(body).appendTo(result);
	
		return result;
	}
	
	//jQuery('.closeChat').live('click', function() {
	//	var thisChat = $(this).closest(".chatHldr");
	//	var thisChatID = $(this).closest(".chatHldr").attr("id");
	//	thisChat.slideUp(function(){
	//		thisChat.remove();
	//	});
	//	delete chats[thisChatID];
	//	console.log("[" + thisChatID + "] Chat closed");
	//});
	//
	//jQuery('.flashHelp a').live('click', function() {
	//	var thisPhono = $(this).closest(".phono");
	//	$(".flash-hldr").css("left", "250.5px");
	//	thisPhono.find(".flashHelp").text("Try again");
	//	return false;
	//});
	//
	//jQuery('.chat').live('click', function() {
	//	var thisPhono = $(this).closest(".phono").attr("id");
	//	var chatTo = $.trim(jQuery("#" + thisPhono).find(".chatTo").val());
	//	//createNewChat(thisPhono, chatTo, "");
	//	openingChatSession(thisPhono, "chatSessionInfo", chatTo, "");
	//});
	//	
	//jQuery('.text').live('click', function() {
	//	var thisPhono = $(this).closest(".phono");
	//	var to = thisPhono.find(".jid").val();
	//	var msg = thisPhono.find(".msgBody").val();
	//	sendMessage(thisPhono.attr("id"), to, msg);
	//	thisPhono.find(".msgBody").val("");
	//});
	//
	//jQuery(".logToggler").click(function() {
	//	if (jQuery("#logConsole").css("height") == "25px") {
	//		jQuery("#logConsole").css("height", "245px");
	//		jQuery("body").css("margin-bottom", "285px");
	//		$(this).text("Hide Log Viewer");
	//	} else {
	//		jQuery("#logConsole").css("height", "25px");
	//		jQuery("body").css("margin-bottom", "25px");
	//		$(this).text("Show Log Viewer");
	//	}
	//
	//	return false;
	//});
	
	jQuery(".players_button").click(function(event){
			event.stopPropagation();
			if(jQuery('.playersWrapper').is(':visible')){
				try{
					jQuery(".playersInner").getNiceScroll().remove(); 
				}catch(e){}
				jQuery('.playersWrapper').slideUp('fast',function() {
				    $(this).remove(); 
				  });
				return;
			}
			
			var wrapper = jQuery('<div class="playersWrapper"/>');
			
			playersPanel = jQuery('<div class="players_title" />');
			playersHeader = jQuery('<span />');
			playersHeader.css('margin-left', '10px');
			playersHeader.text('Players');
			playersPanel.append(playersHeader);
			
			playersInnerPanel = jQuery('<div class="playersInner">');
			
			if(mySessionInfo.friendsList.length > 4){
				playersInnerPanel.height('446px');
			}
			
			if(mySessionInfo.friendsList.length == 0){
				noPlayersListed = jQuery('<div class="player"><a href="javascript:;" class="player_inner"><div class="player_title"></div><div class="player_text">No Players</div><div style="font-weight: bold;" class="notification_date"></div></a></div>');
				playersInnerPanel.append(noPlayersListed);
			}
			else{
			
				jQuery.each(mySessionInfo.friendsList, function(friendId, friendInfo){
							
							singleFriend = jQuery("<div/>");
							singleFriend.addClass("player");
							
							singleFriendLink = jQuery("<a/>");
							singleFriendLink.addClass("player_inner");
							
							singleFriendInfo = jQuery("<div/>");
							singleFriendInfo.addClass("player_title");
							singleFriendInfo.attr("id", friendInfo.userId);
							singleFriendInfo.text(friendInfo.userName);
							singleFriendInfo.click(function(){
								openingChatSession("MyChatSession", "chatSessionInfo", friendId, "");	
							});
							
							singleFriendLink.append(singleFriendInfo);
							singleFriend.append(singleFriendLink);
							playersInnerPanel.append(singleFriend);
							
				});
			}
			wrapper.html(playersPanel);
			wrapper.append(playersInnerPanel);

			jQuery('body').append(wrapper);
			wrapper.slideDown('fast',function() {
				jQuery('.players_title').width(wrapper.width());
			    if(mySessionInfo.friendsList.length > 4){
			    	jQuery('.playersInner').niceScroll();
				}
			  });
			
			wrapper.click(function(event){
			     event.stopPropagation();
			 });
		});
	
	createNewPhono();
	
	
	
});